/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.menu;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.spring.SpringContextHolder;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.SecurityUserHolder;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.service.menu.AppMenusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(value = "/je/rbac/appMenus")
public class AppMenusController extends AbstractPlatformController {

    @Autowired
    private AppMenusService appMenusService;

    /**
     * 加载app菜单
     */
    @RequestMapping(value = "/loadAppMenus", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public JSONObject loadAppMenus(HttpServletRequest request) {
        String departmentId = SecurityUserHolder.getCurrentAccountDepartment().getId();
        String accountId = SecurityUserHolder.getCurrentAccountId();
        String appId = getStringParameter(request, "appId");
        if (Strings.isNullOrEmpty(appId)) {
            throw new PlatformException("参数错误！", PlatformExceptionEnum.UNKOWN_ERROR);
        }

        boolean enableSaas = SpringContextHolder.getBean("enableSaas");
        String tenantId = "";
        if (enableSaas) {
            tenantId = SecurityUserHolder.getCurrentAccountTenantId();
        }

        JSONTreeNode treeNode = appMenusService.loadAppMenus(departmentId,accountId, tenantId, appId);

        List<Map<String, Object>> permdQuickList = appMenusService.loadAppQuickMenus(accountId, tenantId, appId);
        List<Map<String, Object>> permdHistoryList = appMenusService.loadAppHistoryMenus(accountId, tenantId, appId);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("menus", treeNode);
        jsonObject.put("collectMenus", permdQuickList);
        jsonObject.put("historyMenus", permdHistoryList);
        return jsonObject;
    }

    /**
     * 收藏菜单
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/appCollectUserQuickMenu", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult appCollectUserQuickMenu(HttpServletRequest request) {
        String userId = getStringParameter(request, "userId");
        String menuId = getStringParameter(request, "menuId");
        String type = getStringParameter(request, "type");
        String appId = getStringParameter(request, "appId");
        if (Strings.isNullOrEmpty(appId)) {
            return BaseRespResult.errorResult("参数错误，appId为空！");
        }

        if (Strings.isNullOrEmpty(userId)) {
            userId = SecurityUserHolder.getCurrentAccountId();
        }

        if (Strings.isNullOrEmpty(menuId)) {
            return BaseRespResult.errorResult("请选择要收藏的菜单！");
        }

        if (!"collect".equals(type) && !"uncollect".equals(type)) {
            return BaseRespResult.errorResult("请选择要进行的操作");
        }

        if ("collect".equals(type)) {
            metaService.executeSql("UPDATE JE_CORE_KJMENU SET SY_ORDERINDEX=SY_ORDERINDEX+1 WHERE KJMENU_YHUD = {0} AND KJMENU_TYPE={1} AND KJMENU_APPID ={2}", userId, "app", appId);
            DynaBean quickMenuBean = new DynaBean("JE_CORE_KJMENU", false);
            quickMenuBean.set("KJMENU_YHUD", userId);
            quickMenuBean.set("KJMENU_CDID", menuId);
            quickMenuBean.set("SY_ORDERINDEX", 1);
            quickMenuBean.set("SY_STATUS", "1");
            quickMenuBean.set("KJMENU_APPID", appId);
            quickMenuBean.set("KJMENU_TYPE", "app");
            commonService.buildModelCreateInfo(quickMenuBean);
            metaService.insert(quickMenuBean);
            return BaseRespResult.successResult("收藏成功！");
        }

        //将重复的删除
        metaService.delete("JE_CORE_KJMENU", ConditionsWrapper.builder().eq("KJMENU_YHUD", userId)
                .eq("KJMENU_CDID", menuId)
                .eq("KJMENU_TYPE", "app")
                .eq("KJMENU_APPID", appId));
        return BaseRespResult.successResult("取消收藏成功！");
    }

    /**
     * 删除收藏菜单
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/removeAppQuickMenus", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult removeAppQuickMenus(HttpServletRequest request) {
        String userId = getStringParameter(request, "userId");
        String menuIds = getStringParameter(request, "menuIds");
        String appId = getStringParameter(request, "appId");
        if (Strings.isNullOrEmpty(appId)) {
            return BaseRespResult.errorResult("参数错误，appId为空！");
        }
        if (Strings.isNullOrEmpty(userId)) {
            userId = SecurityUserHolder.getCurrentAccountId();
        }
        if (Strings.isNullOrEmpty(menuIds)) {
            return BaseRespResult.errorResult("请选择要删除的快捷菜单！");
        }

        List<String> menuIdList = Splitter.on(",").splitToList(menuIds);
        metaService.delete("JE_CORE_KJMENU", ConditionsWrapper.builder()
                .eq("KJMENU_YHUD", userId)
                .eq("KJMENU_TYPE", "app")
                .eq("KJMENU_APPID", appId)
                .in("KJMENU_CDID", menuIdList));
        return BaseRespResult.successResult("取消收藏成功！");
    }

    /**
     * 修改收藏菜单
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateAppQuickMenus", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult updateAppQuickMenus(HttpServletRequest request) {
        String userId = getStringParameter(request, "userId");
        String menuIds = getStringParameter(request, "menuIds");
        String appId = getStringParameter(request, "appId");
        if (Strings.isNullOrEmpty(appId)) {
            return BaseRespResult.errorResult("参数错误，appId为空！");
        }
        if (Strings.isNullOrEmpty(menuIds)) {
            return BaseRespResult.errorResult("请选择要更新的菜单！");
        }

        if (Strings.isNullOrEmpty(userId)) {
            userId = SecurityUserHolder.getCurrentAccountId();
        }

        List<String> menuIdList = Splitter.on(",").splitToList(menuIds);
        metaService.delete("JE_CORE_KJMENU", ConditionsWrapper.builder()
                .eq("KJMENU_YHUD", userId)
                .eq("KJMENU_TYPE", "app")
                .eq("KJMENU_APPID", appId)
                .in("KJMENU_CDID", menuIdList));
        for (int i = 0; i < menuIdList.size(); i++) {
            DynaBean quickMenuBean = new DynaBean("JE_CORE_KJMENU", false);
            quickMenuBean.set("KJMENU_YHUD", userId);
            quickMenuBean.set("KJMENU_CDID", menuIdList.get(i));
            quickMenuBean.set("SY_ORDERINDEX", i + 1);
            quickMenuBean.set("SY_STATUS", "1");
            quickMenuBean.set("KJMENU_TYPE", "app");
            quickMenuBean.set("KJMENU_APPID", appId);
            commonService.buildModelCreateInfo(quickMenuBean);
            metaService.insert(quickMenuBean);
        }
        return BaseRespResult.successResult("更新成功！");
    }

    /**
     * 添加菜单历史
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/appRecordMenuHistory", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult appRecordMenuHistory(HttpServletRequest request) {
        String userId = getStringParameter(request, "userId");
        String menuId = getStringParameter(request, "menuId");
        String appId = getStringParameter(request, "appId");
        if (Strings.isNullOrEmpty(appId)) {
            return BaseRespResult.errorResult("参数错误，appId为空！");
        }
        if (Strings.isNullOrEmpty(menuId)) {
            return BaseRespResult.errorResult("请选择要记录的菜单！");
        }
        String userName = "";
        if (Strings.isNullOrEmpty(userId)) {
            userId = SecurityUserHolder.getCurrentAccountId();
            userName = SecurityUserHolder.getCurrentAccountName();
        }

        DynaBean recordBean = metaService.selectOne("JE_RBAC_MENUHISTORY", ConditionsWrapper.builder()
                .eq("JE_CORE_MENU_ID", menuId)
                .eq("MENUHISTORY_USER_ID", userId)
                .eq("MENUHISTORY_APPID", appId));
        if (recordBean == null) {
            recordBean = new DynaBean("JE_RBAC_MENUHISTORY", false);
            recordBean.set("JE_CORE_MENU_ID", menuId);
            recordBean.set("MENUHISTORY_USER_ID", userId);
            recordBean.set("MENUHISTORY_USER_NAME", userName);
            recordBean.set("MENUHISTORY_CZSJ", DateUtils.formatDate(new Date(), DateUtils.DAFAULT_DATETIME_FORMAT));

            recordBean.set("MENUHISTORY_APPID", appId);
            commonService.buildModelCreateInfo(recordBean);
            metaService.insert(recordBean);
        } else {
            recordBean.set("MENUHISTORY_CZSJ", DateUtils.formatDate(new Date(), DateUtils.DAFAULT_DATETIME_FORMAT));
            commonService.buildModelModifyInfo(recordBean);
            metaService.update(recordBean);
        }

        return BaseRespResult.successResult(recordBean);
    }

    /**
     * 删除菜单历史
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/removeAppMenuHistory", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult removeAppMenuHistory(HttpServletRequest request) {
        String userId = getStringParameter(request, "userId");
        String menuIds = getStringParameter(request, "menuIds");
        String appId = getStringParameter(request, "appId");
        if (Strings.isNullOrEmpty(appId)) {
            return BaseRespResult.errorResult("参数错误，appId为空！");

        }
        if (Strings.isNullOrEmpty(userId)) {
            userId = SecurityUserHolder.getCurrentAccountId();
        }
        if (Strings.isNullOrEmpty(menuIds)) {
            metaService.delete("JE_RBAC_MENUHISTORY", ConditionsWrapper.builder()
                    .eq("MENUHISTORY_USER_ID", userId)
                    .eq("MENUHISTORY_APPID", appId));
        } else {
            metaService.delete("JE_RBAC_MENUHISTORY", ConditionsWrapper.builder()
                    .eq("MENUHISTORY_USER_ID", userId)
                    .eq("MENUHISTORY_APPID", appId)
                    .in("JE_CORE_MENU_ID", Splitter.on(",").splitToList(menuIds)));
        }
        return BaseRespResult.successResult("删除成功！");
    }
}
